package com.bear.atlassianmcp.jira.mcp.tools;

import com.bear.atlassianmcp.jira.model.JiraProject;
import com.bear.atlassianmcp.jira.model.JiraSearchResult;
import com.bear.atlassianmcp.jira.model.JiraUser;
import com.bear.atlassianmcp.jira.service.JiraService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 项目管理MCP工具
 * 提供项目查询、项目Issues统计等功能
 */
@Service
public class ProjectTools {

    private static final Logger logger = LoggerFactory.getLogger(ProjectTools.class);

    private final JiraService jiraService;

    @Autowired
    public ProjectTools(JiraService jiraService) {
        this.jiraService = jiraService;
    }

    /**
     * 获取所有可访问的项目列表
     * 
     * @return 项目列表的格式化文本
     */
    @Tool(description = "获取当前用户可以访问的所有Jira项目列表，包括项目键、名称、描述等信息",returnDirect=true)
    public String getProjects(ToolContext toolContext) {
        logger.info("MCP Tool: Getting all projects");
        
        try {
            List<JiraProject> projects = jiraService.getProjects(toolContext);
            
            if (projects.isEmpty()) {
                return "📁 当前没有可访问的项目。";
            }
            
            StringBuilder result = new StringBuilder();
            result.append(String.format("📁 可访问的项目列表 (共%d个)：\n\n", projects.size()));
            
            for (int i = 0; i < projects.size(); i++) {
                JiraProject project = projects.get(i);
                result.append(String.format("%d. %s (%s)\n", 
                                           i + 1, project.getName(), project.getKey()));
                
                if (project.getDescription() != null && !project.getDescription().trim().isEmpty()) {
                    String desc = project.getDescription();
                    if (desc.length() > 100) {
                        desc = desc.substring(0, 100) + "...";
                    }
                    result.append(String.format("   描述: %s\n", desc));
                }
                
                if (project.getLeadName() != null) {
                    result.append(String.format("   负责人: %s\n", project.getLeadName()));
                }
                
                result.append("\n");
            }
            
            logger.info("Successfully retrieved {} projects via MCP", projects.size());
            return result.toString();
            
        } catch (Exception e) {
            logger.error("Failed to get projects via MCP: {}", e.getMessage());
            return "❌ 获取项目列表失败。原因：" + e.getMessage();
        }
    }

    /**
     * 获取指定项目的详细信息
     *
     * @param projectKey 项目键值，如"PROJ"
     * @param toolContext 工具上下文
     * @return 项目详细信息的格式化文本
     */
    @Tool(description = "获取指定项目的详细信息，包括项目配置、Issue类型、版本等")
    public String getProject(@ToolParam(description = "项目键值，如PROJ、DEMO等，可通过getProjects工具获取可用项目列表") String projectKey, ToolContext toolContext) {
        logger.info("MCP Tool: Getting project details for {}", projectKey);

        try {
            JiraProject project = jiraService.getProject(projectKey, toolContext);
            String result = project.toFormattedString();

            logger.info("Successfully retrieved project {} via MCP", projectKey);
            return result;

        } catch (Exception e) {
            logger.error("Failed to get project {} via MCP: {}", projectKey, e.getMessage());
            return "❌ 获取项目详情失败。原因：" + e.getMessage();
        }
    }

    /**
     * 获取项目的Issues统计
     * 
     * @param projectKey 项目键值
     * @return 项目Issues统计信息
     */
    @Tool(description = "获取指定项目的Issues统计信息，包括总数、各状态分布等")
    public String getProjectIssues(@ToolParam(description = "项目键值，如PROJ、DEMO等") String projectKey, ToolContext context) {
        logger.info("MCP Tool: Getting project issues for {}", projectKey);
        
        try {
            JiraSearchResult result = jiraService.getProjectIssues(projectKey, context);
            
            if (result.getTotal() == 0) {
                return String.format("📊 项目 %s 当前没有Issues。", projectKey);
            }
            
            String formattedResult = String.format("📊 项目 %s 的Issues：\n%s", 
                                                  projectKey, result.toFormattedString());
            
            logger.info("Successfully retrieved project issues for {} via MCP: {} issues", 
                       projectKey, result.getTotal());
            return formattedResult;
            
        } catch (Exception e) {
            logger.error("Failed to get project issues for {} via MCP: {}", projectKey, e.getMessage());
            return "❌ 获取项目Issues失败。原因：" + e.getMessage();
        }
    }

    /**
     * 获取项目中指定状态的Issues
     * 
     * @param projectKey 项目键值
     * @param status 状态名称，如"Open"、"In Progress"、"Done"等
     * @return 指定状态的Issues列表
     */
    @Tool(description = "获取项目中指定状态的Issues，常用状态包括Open、In Progress、Done等")
    public String getProjectIssuesByStatus(@ToolParam(description = "项目键值，如PROJ、DEMO等") String projectKey,
                                          @ToolParam(description = "Issue状态名称，如Open、In Progress、Done、Closed等") String status,
                                          ToolContext context) {
        logger.info("MCP Tool: Getting project {} issues with status {}", projectKey, status);
        
        try {
            JiraSearchResult result = jiraService.getProjectIssuesByStatus(projectKey, status, context);
            
            if (result.getTotal() == 0) {
                return String.format("📊 项目 %s 中没有状态为 \"%s\" 的Issues。", projectKey, status);
            }
            
            String formattedResult = String.format("📊 项目 %s 中状态为 \"%s\" 的Issues：\n%s", 
                                                  projectKey, status, result.toFormattedString());
            
            logger.info("Successfully retrieved project {} issues with status {} via MCP: {} issues", 
                       projectKey, status, result.getTotal());
            return formattedResult;
            
        } catch (Exception e) {
            logger.error("Failed to get project {} issues with status {} via MCP: {}", 
                        projectKey, status, e.getMessage());
            return "❌ 获取项目指定状态Issues失败。原因：" + e.getMessage();
        }
    }

    /**
     * 获取当前用户信息
     * 
     * @return 当前用户的详细信息
     */
    @Tool(description = "获取当前Jira登录用户的详细信息，包括用户名、邮箱、时区等")
    public String getCurrentUser(ToolContext context) {
        logger.info("MCP Tool: Getting current user info");
        
        try {
            JiraUser user = jiraService.getCurrentUser(context);
            String result = user.toFormattedString();
            
            logger.info("Successfully retrieved current user via MCP: {}", user.getDisplayName());
            return "👤 当前用户信息：\n" + result;
            
        } catch (Exception e) {
            logger.error("Failed to get current user via MCP: {}", e.getMessage());
            return "❌ 获取当前用户信息失败。原因：" + e.getMessage();
        }
    }

    /**
     * 测试Jira连接
     * 
     * @return 连接测试结果
     */
    @Tool(description = "测试与Jira服务器的连接状态，验证认证和网络连通性")
    public String testJiraConnection(ToolContext context)  {
        logger.info("MCP Tool: Testing Jira connection");

        try {
            String result = jiraService.testConnection(context);

            logger.info("Successfully tested Jira connection via MCP");
            return "🔗 " + result;

        } catch (Exception e) {
            logger.error("Failed to test Jira connection via MCP: {}", e.getMessage());
            return "❌ 连接测试失败。原因：" + e.getMessage() +
                   "\n💡 请检查Jira服务器地址、用户名和密码配置。";
        }
    }

    /**
     * 获取项目简要信息列表
     * 
     * @return 项目简要信息列表
     */
    @Tool(description = "获取所有项目的简要信息列表，只包含项目键和名称，适合快速浏览")
    public String getProjectsSummary(ToolContext context) {
        logger.info("MCP Tool: Getting projects summary");
        
        try {
            List<JiraProject> projects = jiraService.getProjects(context);
            
            if (projects.isEmpty()) {
                return "📁 当前没有可访问的项目。";
            }
            
            StringBuilder result = new StringBuilder();
            result.append(String.format("📁 项目简要列表 (共%d个)：\n", projects.size()));
            
            for (JiraProject project : projects) {
                result.append(String.format("• %s (%s)", project.getName(), project.getKey()));
                if (project.getLeadName() != null) {
                    result.append(String.format(" - 负责人: %s", project.getLeadName()));
                }
                result.append("\n");
            }
            
            logger.info("Successfully retrieved projects summary via MCP: {} projects", projects.size());
            return result.toString();
            
        } catch (Exception e) {
            logger.error("Failed to get projects summary via MCP: {}", e.getMessage());
            return "❌ 获取项目简要列表失败。原因：" + e.getMessage();
        }
    }

    /**
     * 获取项目统计信息
     * 
     * @param projectKey 项目键值
     * @return 项目统计信息
     */
    @Tool(description = "获取项目的统计信息，包括Issues总数、各状态分布等概览数据")
    public String getProjectStatistics(String projectKey, ToolContext context) {
        logger.info("MCP Tool: Getting project statistics for {}", projectKey);
        
        try {
            // 获取项目基本信息
            JiraProject project = jiraService.getProject(projectKey, context);
            
            // 获取项目所有Issues
            JiraSearchResult allIssues = jiraService.getProjectIssues(projectKey, context);
            
            StringBuilder result = new StringBuilder();
            result.append(String.format("📊 项目 %s (%s) 统计信息：\n\n", 
                                       project.getName(), project.getKey()));
            
            result.append(String.format("📈 Issues总数: %d\n", allIssues.getTotal()));
            
            if (project.getLeadName() != null) {
                result.append(String.format("👤 项目负责人: %s\n", project.getLeadName()));
            }
            
            // 显示最近的几个Issues
            if (allIssues.getIssues() != null && !allIssues.getIssues().isEmpty()) {
                result.append("\n🔍 最近的Issues:\n");
                int count = Math.min(5, allIssues.getIssues().size());
                for (int i = 0; i < count; i++) {
                    var issue = allIssues.getIssues().get(i);
                    result.append(String.format("• %s - %s (%s)\n", 
                                               issue.getKey(), issue.getSummary(), issue.getStatus()));
                }
                
                if (allIssues.getTotal() > count) {
                    result.append(String.format("... 还有 %d 个Issues\n", allIssues.getTotal() - count));
                }
            }
            
            logger.info("Successfully retrieved project statistics for {} via MCP", projectKey);
            return result.toString();
            
        } catch (Exception e) {
            logger.error("Failed to get project statistics for {} via MCP: {}", projectKey, e.getMessage());
            return "❌ 获取项目统计信息失败。原因：" + e.getMessage();
        }
    }
}
